var util = require('../../utils/util.js');
var wxCharts = require('../../ext/wxcharts-min.js');
import * as echarts from '../../ext/ec-canvas/echarts';
var wx_request = require('../../ext/wx-request.js');

const app = getApp();
const finance_overall_url = require('../../config').finance_overall_url;
const finance_project_url = require('../../config').finance_project_url;

var ysTop10Data = { "cloumn": [], "data": [] };
var yfTop10Data = { "cloumn": [], "data": [] };
var mlTop10Data = { "cloumn": [], "data": [] };
var mllTop10Data = { "cloumn": [], "data": [] };

function test() {
  for(var i= 0; i<10; i++) {
    ysTop10Data.cloumn.push('应收' + i);
    ysTop10Data.data.push((Math.random() * 10 + 10).toFixed(2));

    yfTop10Data.cloumn.push('应付' + i);
    yfTop10Data.data.push((Math.random() * 10 + 10).toFixed(2));

    mlTop10Data.cloumn.push('毛利' + i);
    mlTop10Data.data.push((Math.random() * 10 + 10).toFixed(2));

    mllTop10Data.cloumn.push('毛利率' + i);
    mllTop10Data.data.push((Math.random() * 10 + 10).toFixed(2));

  }
}

function dealData(page) {
  ysTop10Data = { "cloumn": [],  "data": [] };
  yfTop10Data = { "cloumn": [],  "data": [] };
  mlTop10Data = { "cloumn": [],  "data": [] };
  mllTop10Data= { "cloumn": [],  "data": [] };
  var pageData = page.data;
  
  var receiverTotalTop = pageData.tableData.receiverTotalTop;
  var payTotalTop = pageData.tableData.payTotalTop;

  var monthInComeRateTop = pageData.tableData2.monthInComeRateTop;
  var monthIncomeTop = pageData.tableData2.monthIncomeTop;
  var yearIncomeTop = pageData.tableData2.yearIncomeTop;
  var yearInComeRateTop = pageData.tableData2.yearInComeRateTop;

  if (pageData.tabIndex == 0) {
    for (var value of receiverTotalTop) {
      ysTop10Data.cloumn.push(value.name);
      ysTop10Data.cloumn.push(value.receiverTotalTop);
    }

    for (var value of payTotalTop) {
      yfTop10Data.cloumn.push(value.name);
      yfTop10Data.cloumn.push(value.payTotalTop);
    }
  } else {
    if (pageData.radioIndex1 == 0) {
      for (var value of monthIncomeTop) {
        mlTop10Data.cloumn.push(value.name);
        mlTop10Data.data.push(value.monthIncome);
      }
      for (var value of monthInComeRateTop) {
        mllTop10Data.cloumn.push(value.name);
        mllTop10Data.cloumn.push(value.monthIncomeRate);
      }
    }else {
      for (var value of yearIncomeTop) {
        mlTop10Data.cloumn.push(value.name);
        mlTop10Data.data.push(value.yearIncome);
      }
      for (var value of yearInComeRateTop) {
        mllTop10Data.cloumn.push(value.name);
        mllTop10Data.cloumn.push(value.yearIncomeRate);
      }
    }
  }
  
}

function setOption(chart, tabIndex, radioIndex) {
  console.log(tabIndex, radioIndex);
  var chartData;
  if (tabIndex == 0) {
    if (radioIndex ==0 ) {
      chartData = ysTop10Data;
    }else {
      chartData = yfTop10Data;
    }
  }else {
    if (radioIndex == 0) {
      chartData = mlTop10Data;
    } else {
      chartData = mllTop10Data;
    }
  }

  // console.log(chartData);
  if(chartData.data.length ==0) {
    test();
  }

  const option = {
    color: ['#37a2da', '#32c5e9', '#67e0e3'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    legend: {
      // data: ['热度', '正面', '负面']
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: [
      {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      }
    ],
    yAxis: [
      {
        type: 'category',
        axisTick: { show: false },
        data: chartData.cloumn,
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      }
    ],
    series: [
      {
        name: '',
        type: 'bar',
        label: {
          normal: {
            show: true,
            position: 'inside'
          }
        },
        data: chartData.data,
        itemStyle: {
          // emphasis: {
          //   color: '#37a2da'
          // }
        }
      }
    ]
  };
  chart.setOption(option);
}


Page({
  data: {
    date: util.formatDate(new Date()),
    tabIndex: 1,
    radioIndex: 0,
    radioIndex1: 0,
    radioIndex2: 0,
    tableData: {
      "receiverTotal": 0,
      "payTotal": 0
    },
    tableData2: {
      "receiverYearTotal": 0,
      "payMonthTotal": 0,
      "payYearTotal": 0,
      "receiverMonthTotal": 0
    },
    tableData2_ext: {
      "sr" : 0,
      "cb": 0,
      "ml": 0,
      "mll": 0
    },
    items: [
      { name: '应收前十', value: 0, checked: 'true' },
      { name: '应付前十', value: 1 }
    ],
    items2: [
      { name: '月度', value: 0, checked: 'true' },
      { name: '年度', value: 1 }
    ],
    items3: [
      { name: '毛利前十', value: 0, checked: 'true' },
      { name: '毛利率前十', value: 1 }
    ],
    ec: {
      lazyLoad: true
    }
  },

  onLoad: function () {
    var page = this;
    this.ecComponent = this.selectComponent('#mychart-dom-bar');
    this.ecComponent2 = this.selectComponent('#mychart-dom-bar2');
    this.updateData();


  },

  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    });
    this.updateData();
  },

  tabChanged: function (e) {
    console.log(e.target.dataset);
    this.setData({
      tabIndex: e.target.dataset.index,
    })
    this.updateData();
  },

  touchHandler: function (e) {
    // console.log(lineChart.getCurrentDataIndex(e));
    if (!lineChart) {
      return;
    }
    console.log(lineChart);
    lineChart.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        // return category + '日' + item.name + ':' + item.data
        return category + '日收入:\r\r\r' + item.data
      }
    });
  },

  updateData: function () {
    var page = this;
    if (page.data.tabIndex == 0) {
      wx_request(this, finance_overall_url + encodeURI(this.data.date + ' 00:00:00'), app.globalData.user_token.token, function (data) {
        page.setData({
          tableData: data
        });
        
        dealData(page);

        page.ecComponent.init((canvas, width, height) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height
          });
          setOption(chart, page.data.tabIndex, page.data.radioIndex);
          page.chart = chart;
          page.setData({
            isLoaded: true,
            isDisposed: false
          });
          return chart;
        });
      });
    }else {
      wx_request(this, finance_project_url + encodeURI(this.data.date + ' 00:00:00'), app.globalData.user_token.token, function (data) {
        page.setData({
          tableData2: data
        });
        page.clacValue();
        
        dealData(page);

        page.ecComponent2.init((canvas, width, height) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height
          });
          setOption(chart, page.data.tabIndex, page.data.radioIndex2);
          page.chart = chart;
          page.setData({
            isLoaded: true,
            isDisposed: false
          });
          return chart;
        });
      });
    }
    
  },

  radioChange: function(e) {
    var page = this;
    var current = e.detail.value;
    this.setData({
      radioIndex: current
    });
    this.ecComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      setOption(chart, page.data.tabIndex, current);
      this.chart = chart;
      return chart;
    });
  },

  clacValue : function() {
    var page = this;
    var current = this.data.radioIndex1;
    var sr, cb;
    if (current == 0) {
      sr = this.data.tableData2.receiverMonthTotal;
      cb = this.data.tableData2.payMonthTotal;
    } else {
      sr = this.data.tableData2.receiverYearTotal;
      cb = this.data.tableData2.payYearTotal;
    }
    var ml = sr - cb;

    var mll = cb == 0 ? cb : ml / cb;
    console.log('收入' + ml + '成本' + ml +  '毛利' + ml + '毛利率' + mll);
    this.setData({
      tableData2_ext: {
        "sr": sr,
        "cb": cb,
        "ml": ml,
        "mll": mll
      }
    });
  },

  radioChange1: function (e) {
    
    var page = this;
    var current = e.detail.value;
    this.setData({
      radioIndex1: current
    });
    this.clacValue();
   
    
  },
  radioChange2: function (e) {
    var page = this;
    var current = e.detail.value;
    this.setData({
      radioIndex2: current
    })
    this.ecComponent2.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      setOption(chart, page.data.tabIndex, current);
      this.chart = chart;
      return chart;
    });
  }

  

})


